import { ElMessage } from 'element-plus'
import { login as loginApi, getUserByPhone } from '../../api/user'
import router from '../../router/index'
export default {
    namespaced: true,
    state: () => ({
        token: sessionStorage.getItem('token') || '',
        currentUser: JSON.parse(sessionStorage.getItem('currentUser')!) || {}
    }),
    mutations: {
        setToken(state: any, data: string) {
            state.token = data
            window.sessionStorage.setItem('token', data)
        },
        setUser(state: any, data: any) {
            state.currentUser = data
            debugger
            window.sessionStorage.setItem('currentUser', JSON.stringify(data))
        }
    },
    actions: {
        login({ commit }: any, data: any) {
            return new Promise<void>((resolve, reject) => {
                loginApi(data).then((res: any) => {
                    if(res.code == 200) {
                        commit('setToken', res.data.token)
                        commit('setUser', res.data)
                        router.replace('/index')
                        ElMessage.success(res.msg)
                        resolve(res)
                        console.log(res.data.token, res.data);
                    }else{
                        ElMessage.error(res.msg)
                        reject(res)
                    }
                })
                .catch((err: any) => reject(err))
            })
       },
    }
}